package com.tanhua.server.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.tanhua.server.utils.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class RedisCacheInterceptor implements HandlerInterceptor {

    @Value("${tanhua.cache.enable}")
    private Boolean casheEnable;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断缓存开关
        if(!casheEnable)
            return true;

        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        if(!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)) {
            return true;
        }

        if(!((HandlerMethod) handler).hasMethodAnnotation(Cache.class)) {
            return true;
        }


        String redisKey = createRedisKey(request);
        String cacheData = redisTemplate.opsForValue().get(redisKey);
        if(StrUtil.isEmpty(cacheData)) {
            //如果为空,则进入controller
            return true;
        }

        //如果不为空
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(cacheData);

        return false;
    }

    /**
     * 生成redis中的key，规则：SERVER_CACHE_DATA_MD5(url + param + token)
     *
     * @param request
     * @return
     */
    public static String createRedisKey(HttpServletRequest request) throws Exception {
        String requestURI = request.getRequestURI();

        Map<String, String[]> parameterMap = request.getParameterMap();
        String jsonStr = JSONUtil.toJsonStr(parameterMap);

        String token = request.getHeader("Authorization");

        String data = requestURI + "_" + jsonStr + "_" + token;

        return "SERVER_CACHE_DATA_" + SecureUtil.md5(data);
    }
}
